{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '0'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate):\n",
    "        \n",
    "        def cells(size_layer, reuse=False):\n",
    "            return tf.nn.rnn_cell.GRUCell(size_layer,reuse=reuse)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        encoder_embedded = tf.nn.embedding_lookup(embeddings, self.X)\n",
    "        \n",
    "        for n in range(num_layers):\n",
    "            (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n",
    "                cell_fw = cells(size_layer // 2),\n",
    "                cell_bw = cells(size_layer // 2),\n",
    "                inputs = encoder_embedded,\n",
    "                sequence_length = self.X_seq_len,\n",
    "                dtype = tf.float32,\n",
    "                scope = 'bidirectional_rnn_%d'%(n))\n",
    "            encoder_embedded = tf.concat((out_fw, out_bw), 2)\n",
    "        \n",
    "        bi_state = tf.concat((state_fw, state_bw), -1)\n",
    "        encoder_state = tuple([bi_state] * num_layers)\n",
    "        \n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        dense = tf.layers.Dense(vocab_size)\n",
    "        decoder_cells = tf.nn.rnn_cell.MultiRNNCell([cells(size_layer) for _ in range(num_layers)])\n",
    "        \n",
    "        training_helper = tf.contrib.seq2seq.TrainingHelper(\n",
    "                inputs = tf.nn.embedding_lookup(embeddings, decoder_input),\n",
    "                sequence_length = self.Y_seq_len,\n",
    "                time_major = False)\n",
    "        training_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                cell = decoder_cells,\n",
    "                helper = training_helper,\n",
    "                initial_state = encoder_state,\n",
    "                output_layer = dense)\n",
    "        training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = training_decoder,\n",
    "                impute_finished = True,\n",
    "                maximum_iterations = tf.reduce_max(self.Y_seq_len))\n",
    "        self.training_logits = training_decoder_output.rnn_output\n",
    "        \n",
    "        predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n",
    "                embedding = embeddings,\n",
    "                start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n",
    "                end_token = EOS)\n",
    "        predicting_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                cell = decoder_cells,\n",
    "                helper = predicting_helper,\n",
    "                initial_state = encoder_state,\n",
    "                output_layer = dense)\n",
    "        predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = predicting_decoder,\n",
    "                impute_finished = True,\n",
    "                maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n",
    "        self.fast_result = predicting_decoder_output.sample_id\n",
    "        \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-7-2056574ff293>:11: GRUCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.GRUCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-2056574ff293>:30: bidirectional_dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.Bidirectional(keras.layers.RNN(cell))`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:464: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:559: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:565: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:575: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:From <ipython-input-7-2056574ff293>:39: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[ 8180,  8180, 13143, 13143, 12937,  6992,  4556,  4556,  9512,\n",
       "         24078, 24078, 20187, 20187, 20187, 20187, 20187,  5649,  5649,\n",
       "          5649, 17526, 17526, 17526, 17526, 10614, 10614, 10614, 17526,\n",
       "          4803,  4803, 18919,  3277, 14446, 14446,   283,   283,   283,\n",
       "           283, 29788, 29788,  1788,  9858,  9858, 28365, 28365, 14894,\n",
       "         14894,  8917,  8917,  8917,  8917,  8917,  8917,  8917,  8917,\n",
       "         24207,  3448,  3448,  2827,  2827, 16308, 16308, 22395, 22395,\n",
       "         22395, 22395, 13721, 13721, 13721, 13721, 13721, 13721, 20560],\n",
       "        [14031, 14031, 30325, 30325, 28000, 28000, 18092, 18092, 18092,\n",
       "         11295, 11295,  1162,  1162,  1162, 10536, 10536, 10536, 25376,\n",
       "         25376, 27602, 27602, 27602,  9451,  9451,  9451, 25158, 25158,\n",
       "         25158, 29397, 29397,  2948, 13433, 13433, 13433, 26233, 21482,\n",
       "         15779, 15779, 15779,     6,  5723,  5723,  5723,  5723,  4474,\n",
       "          4474, 10896, 10896, 25678, 25678, 25678, 25678, 24216, 24216,\n",
       "         24216, 25678, 25678, 26546, 26546, 26546, 26546, 26937, 26937,\n",
       "         26937, 26937, 26937, 13523, 13523,  5507,  5507,  5507, 12237],\n",
       "        [ 3492, 29282,  5618,  5618,  5618, 31371, 15253, 15253,  9594,\n",
       "         26231, 23601, 23601, 23601, 23601, 17818, 17818,   790,   790,\n",
       "         28328, 28328, 28328, 28328, 28328, 21269, 25599, 25599, 20777,\n",
       "         20777, 15509,  7506,  7506,  7506,  7506, 16357, 16357,  9381,\n",
       "         18494, 18494, 18494,   311,   311,   311, 23309, 23309, 29333,\n",
       "         29333, 12678, 12678, 12678,  1266,  1266,  1266,  9769, 12202,\n",
       "         12202, 12202, 12202, 27408, 27408, 27408, 31808, 26305, 26305,\n",
       "         21743, 21743, 21743, 21743, 17298, 17298, 23703, 26614, 26614],\n",
       "        [28527, 11998, 11760,   325,  2733, 13822, 13822, 13822, 13822,\n",
       "         13822, 22734, 16097,   645,   645,  8043,  8043,  8043, 13197,\n",
       "         13197, 31343, 31343, 31343, 25295, 29300, 10570, 10570, 17455,\n",
       "         25557, 25557, 25557, 26040, 26040, 22983, 22983, 22983, 22983,\n",
       "         20252, 20252,   635,   635,  3348,  3348, 22729, 21346, 21346,\n",
       "         16021, 16021, 16021, 16021, 12749, 12749, 12749, 30041,  4115,\n",
       "         13923, 13923, 13923, 13936, 13936, 13936,  2401,  2401,  8540,\n",
       "          8540,  8540,  8540, 14287, 14287, 14287, 29668,  4830, 14553],\n",
       "        [  851, 12789, 29757, 29757, 29757,  6024,  6024, 10217, 10217,\n",
       "         23363, 29120, 29120, 29120, 29120, 16748, 16748, 16748, 16748,\n",
       "         17155, 17155, 27051, 27051, 27051, 29052, 28869, 28869, 28869,\n",
       "         28869, 22650,   519,   519, 30067, 30067, 10499, 10499,  5401,\n",
       "          5401,  5401,  5401, 16051, 16051,  7814,  7814,  7814, 29090,\n",
       "         29090, 25969, 25969, 25969, 18542,  1156,  1156,  1156, 26643,\n",
       "         16021, 20097, 20097,  6948,    30,  9205,  9205, 27371, 27371,\n",
       "         13483, 16565, 16565, 11133, 11133, 11133, 31288, 31288, 19912],\n",
       "        [13022, 13022, 16371, 16371, 16371,  3368,  3368,    36,    36,\n",
       "            36, 14968,  9807,  9807, 17203,  9472,  9472,  9472, 30524,\n",
       "         30524, 17294, 17294, 17294, 17294, 17294, 15839, 15839, 29746,\n",
       "         29746,  8460,  8460,  8460, 27139, 27139, 27139, 12978, 12978,\n",
       "         24962, 29047, 29047, 29047,  1305,  1305,  1365,  1365, 21700,\n",
       "          8701,  8701,  8701, 16461, 16461, 23803,  1572,  1572,  1572,\n",
       "         19844,  7597,  2980, 13411, 13411, 13411, 13411, 27237, 13411,\n",
       "          7861,  7861,  7861,   594,   594,   594, 12504, 27329, 27329],\n",
       "        [23638, 15744, 15744, 29832, 29832, 29832, 16877, 16877, 12119,\n",
       "         12119, 26912, 26912, 26912, 26912,  6204, 12434, 12434, 12434,\n",
       "          3266,  3266, 19456, 19456, 30330,  6281, 30711, 30711, 25006,\n",
       "         25006,  3627,  3627,  1801, 29015, 29015, 26619,  6086, 29585,\n",
       "         29585, 29585, 29585, 29585,  2929,  2929,  2929,  5909, 13884,\n",
       "         31205, 31205, 31205, 27991, 27991, 27991, 23283, 23283, 23283,\n",
       "          9129, 26896, 26896, 26896, 24066, 24066, 24066, 24066, 11033,\n",
       "          1223,  1223,  1223, 16497, 16497, 16497, 16497, 30817, 30817],\n",
       "        [31090, 31090, 25561, 25561, 11564,  8687, 12853,  1309,  1309,\n",
       "          1046,  8824,  1046, 25155,  9532,  9532,  9532,  9532,  9532,\n",
       "         30968, 30968, 30968,  3295,  3295,  3295,  6262, 16557,  7667,\n",
       "          6262,  8595, 26006, 26006, 26006, 26006, 24995, 24995, 24995,\n",
       "          3736, 31373, 31373, 31373, 27791, 27791, 30818, 30818, 27791,\n",
       "         27791, 10868, 10868, 10868, 26871, 26871,   643,  9724,  5304,\n",
       "          5304,  5304,  5304,  5304, 16036,    39, 18772, 18772, 11257,\n",
       "         11257, 17203, 17203, 17203,  3303,  3303,  3303,  3303,  3303],\n",
       "        [ 5876,  5876,  5876,  5876,  5876, 29670,  3887, 21589, 21589,\n",
       "         21589,  8786, 17782, 17782, 17782,  8173, 16003, 16003, 21320,\n",
       "         21320, 21320, 21320, 21320, 21320, 17757, 16209, 21990, 21990,\n",
       "         21990, 18542, 18542, 18542, 23119, 23119, 13178, 13178, 13178,\n",
       "         13178, 25956, 25956, 12976, 12976,  9614, 26583, 26583, 20131,\n",
       "         20131, 20131, 14467, 14467, 22113, 28238, 28595, 28595, 28595,\n",
       "         28595,  4721,  4721,  4721,  8331,  8331,  8331, 10321, 15239,\n",
       "         15239,  3135,  3135,  3611,  3611, 31969, 13551, 11837, 23029],\n",
       "        [21806, 16704, 27802, 30047, 30047, 26475, 11241, 19047, 19047,\n",
       "         19047, 11241, 11241, 11241, 18943, 18943, 18943, 18943, 18943,\n",
       "         18943, 18943, 25417,  8242, 23925, 23925, 23925, 23925, 23925,\n",
       "         23925, 17979, 17979, 17979, 30056, 30056, 30056,  9887,  9887,\n",
       "          6893, 26938, 26938, 26938, 26938,   429,   429,  8681,  8681,\n",
       "         24514, 24514,  2940,  2940,  2940, 21755, 21755, 15425, 28381,\n",
       "         15425, 29021,  2353,  2353,  2353,  3880,  3880,  3880,  3880,\n",
       "          3880, 15365,  5083, 15762, 17282, 17282, 14841, 14841, 14841]],\n",
       "       dtype=int32), 10.374331, 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:24<00:00,  2.28it/s, accuracy=0.257, cost=4.7] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.86it/s, accuracy=0.296, cost=4.07]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 5.912079, training avg acc 0.166160\n",
      "epoch 1, testing avg loss 4.506110, testing avg acc 0.262045\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:27<00:00,  2.27it/s, accuracy=0.332, cost=3.72]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.91it/s, accuracy=0.339, cost=3.52]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 4.049781, training avg acc 0.306016\n",
      "epoch 2, testing avg loss 3.832899, testing avg acc 0.329587\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:38<00:00,  2.24it/s, accuracy=0.411, cost=3]   \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.85it/s, accuracy=0.371, cost=3.26]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 3.400880, training avg acc 0.371896\n",
      "epoch 3, testing avg loss 3.594582, testing avg acc 0.356842\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:44<00:00,  2.22it/s, accuracy=0.488, cost=2.45]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.86it/s, accuracy=0.376, cost=3.14]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 2.997944, training avg acc 0.418057\n",
      "epoch 4, testing avg loss 3.527262, testing avg acc 0.366554\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:45<00:00,  2.22it/s, accuracy=0.564, cost=2.04]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.84it/s, accuracy=0.409, cost=3.12]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 2.707116, training avg acc 0.455160\n",
      "epoch 5, testing avg loss 3.531936, testing avg acc 0.369929\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:47<00:00,  2.21it/s, accuracy=0.62, cost=1.74] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.95it/s, accuracy=0.409, cost=3.11]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 2.482041, training avg acc 0.486549\n",
      "epoch 6, testing avg loss 3.580899, testing avg acc 0.367816\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:36<00:00,  2.24it/s, accuracy=0.68, cost=1.52] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.88it/s, accuracy=0.409, cost=3.18]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 2.304343, training avg acc 0.512776\n",
      "epoch 7, testing avg loss 3.655856, testing avg acc 0.362913\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:31<00:00,  2.26it/s, accuracy=0.691, cost=1.36]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.93it/s, accuracy=0.403, cost=3.07]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 2.160954, training avg acc 0.534549\n",
      "epoch 8, testing avg loss 3.737370, testing avg acc 0.358621\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:34<00:00,  2.25it/s, accuracy=0.706, cost=1.3] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.83it/s, accuracy=0.392, cost=3.14]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 2.040770, training avg acc 0.552979\n",
      "epoch 9, testing avg loss 3.815466, testing avg acc 0.353772\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:42<00:00,  2.22it/s, accuracy=0.737, cost=1.16]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.89it/s, accuracy=0.376, cost=3.18]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 1.930049, training avg acc 0.570824\n",
      "epoch 10, testing avg loss 3.895134, testing avg acc 0.353186\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:37<00:00,  2.24it/s, accuracy=0.764, cost=1.06]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.92it/s, accuracy=0.392, cost=3.21]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 1.833433, training avg acc 0.586451\n",
      "epoch 11, testing avg loss 3.991868, testing avg acc 0.349418\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:39<00:00,  2.23it/s, accuracy=0.748, cost=1.06]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.90it/s, accuracy=0.355, cost=3.34]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 1.756140, training avg acc 0.598503\n",
      "epoch 12, testing avg loss 4.059681, testing avg acc 0.346714\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:40<00:00,  2.23it/s, accuracy=0.775, cost=0.968]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.91it/s, accuracy=0.387, cost=3.35]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 1.686734, training avg acc 0.609522\n",
      "epoch 13, testing avg loss 4.143593, testing avg acc 0.345248\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:36<00:00,  2.24it/s, accuracy=0.796, cost=0.889]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.89it/s, accuracy=0.376, cost=3.38]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 1.622047, training avg acc 0.620016\n",
      "epoch 14, testing avg loss 4.241367, testing avg acc 0.344546\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:34<00:00,  2.25it/s, accuracy=0.8, cost=0.882] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.97it/s, accuracy=0.403, cost=3.47]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 1.568954, training avg acc 0.628421\n",
      "epoch 15, testing avg loss 4.302605, testing avg acc 0.342172\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:27<00:00,  2.27it/s, accuracy=0.797, cost=0.837]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.97it/s, accuracy=0.376, cost=3.52]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 1.523960, training avg acc 0.635393\n",
      "epoch 16, testing avg loss 4.380991, testing avg acc 0.338359\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:25<00:00,  2.28it/s, accuracy=0.809, cost=0.801]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.92it/s, accuracy=0.382, cost=3.57]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 1.482213, training avg acc 0.641733\n",
      "epoch 17, testing avg loss 4.450799, testing avg acc 0.337775\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:24<00:00,  2.28it/s, accuracy=0.82, cost=0.748]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.99it/s, accuracy=0.382, cost=3.73]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 1.443569, training avg acc 0.647991\n",
      "epoch 18, testing avg loss 4.534051, testing avg acc 0.334935\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:26<00:00,  2.28it/s, accuracy=0.812, cost=0.739]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.93it/s, accuracy=0.403, cost=3.67]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 1.407701, training avg acc 0.653678\n",
      "epoch 19, testing avg loss 4.622604, testing avg acc 0.330094\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:26<00:00,  2.28it/s, accuracy=0.834, cost=0.677]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.04it/s, accuracy=0.387, cost=3.72]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 1.372407, training avg acc 0.659821\n",
      "epoch 20, testing avg loss 4.666390, testing avg acc 0.331290\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [00:19<00:00,  2.02it/s]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0.047413725"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from tensor2tensor.utils import bleu_hook\n",
    "\n",
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)\n",
    "    \n",
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])\n",
    "    \n",
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
